import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/home.vue';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { usePermissStore } from '@/store/permiss';
import { v4 as uuidv4 } from 'uuid';

const importRoute = import.meta.glob('../views/**/*.vue');

const routes: RouteRecordRaw[] = [
    {
        path: '/',
        name: '系统首页',
        component: Home,
        redirect: '/dashboard',
        children: [
            {
                path: '/dashboard',
                name: '系统首页',
                component: () => import(/* webpackChunkName: "dashboard" */ '../views/dashboard.vue'),
            },
            {
                path: '/userCenter',
                name: '个人中心',
                component: () => import(/* webpackChunkName: "userCenter" */"../views/userCenter/index.vue"),
            },
            // {
            //     path: '/messages',
            //     name: '消息中心',
            //     component: () => import(/* webpackChunkName: "messages" */ "../views/messages.vue"),
            // }

        ],
    },
    {
        path: '/login',
        name: '登录',
        meta: {
            title: '登录',
        },
        component: () => import(/* webpackChunkName: "login" */ '../views/login.vue'),
    },
    {
        path: '/403',
        name: '403',
        meta: {
            title: '没有权限',
        },
        component: () => import(/* webpackChunkName: "403" */ '../views/403.vue'),
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});
router.beforeEach((to, from, next) => {
    const permiss = usePermissStore();

    NProgress.start();
    const whiteList = ["/login", "/403", "/"]
    let token = sessionStorage.getItem("token");
    let hasRoutes = permiss.hasRoutes;
    let menuList = JSON.parse(sessionStorage.getItem("menuList") || "{}");
    if (token) {
        if (!hasRoutes) {
            bindRoute(menuList, to.path)
            permiss.setRouteState(true);
            next({
                ...to,
                replace: true
            })
        } else {
            next()
        }

    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next("/login")
        }
    }
})
//登录后
router.afterEach(transition => {
    NProgress.done();
});

//动态绑定路由
const bindRoute = (menuList: any[], path: string) => {
    let newRoutes = router.options.routes;
    newRoutes[0].children = [{
        path: '/dashboard',
        name: '系统首页',
        component: () => import(/* webpackChunkName: "dashboard" */ '../views/dashboard.vue'),
    }, {
        path: '/userCenter',
        name: '个人中心',
        component: () => import(/* webpackChunkName: "userCenter" */ "../views/userCenter/index.vue"),
    }
    ]
    menuList.forEach((menu) => {
        if (menu.children) {
            menu.children.forEach((m: any) => {
                if (m.children.length) {
                    m.children.forEach((t: any) => {
                        let route_t = menuToRoute(t, m.name);
                        if (route_t) {
                            const result: any = newRoutes[0].children
                            result.push(route_t);
                        }
                    })
                }
                else {
                    let route = menuToRoute(m, menu.name);
                 
                    if (route) {
                        const result: any = newRoutes[0].children
                        result.push(route);
                    }
                }

            })
        }
    })
    //重现添加到路由
    newRoutes.forEach(route => {
        router.addRoute(route);
    })
}

const menuToRoute = (menu: any, parentName: any) => {
    if (!menu.component) return null;
    else {

        let route: any = {
            name: menu.name,
            key: uuidv4(),
            path: menu.path,
            meta: {
                parentName: parentName
            },
            component: importRoute["../views/" + menu.component + '.vue']
        }
        return route;
    }
}

export default router;
